/*
 * Copyright (c) 2022 Kirky
 * Licensed under the Open Software Licence, Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://opensource.org/licenses/osl-3.0.php
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lingeringdream.luciole;

import com.lingeringdream.luciole.helper.ResourceHelper;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.component.AlbumsSpinner;
import com.zhihu.matisse.component.CheckRadioView;
import com.zhihu.matisse.listener.LoaderCallback;
import com.zhihu.matisse.loader.AlbumLoader;
import com.zhihu.matisse.loader.ResultSetLoader;
import com.zhihu.matisse.model.Album;
import com.zhihu.matisse.model.Item;
import com.zhihu.matisse.model.SelectedItemCollection;
import com.zhihu.matisse.model.SelectionSpec;
import com.zhihu.matisse.provider.AlbumsAdapter;
import com.zhihu.matisse.provider.MediaProvider;
import com.zhihu.matisse.slice.SelectPreviewAbility;
import com.zhihu.matisse.utils.IncapableDialog;
import com.zhihu.matisse.utils.L;
import com.zhihu.matisse.utils.PhotoMetadataUtils;
import com.zhihu.matisse.utils.UIUtils;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
import ohos.agp.utils.Color;
import ohos.agp.utils.Point;
import ohos.agp.window.service.DisplayManager;
import ohos.agp.window.service.WindowManager;
import ohos.data.resultset.ResultSet;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;
import ohos.utils.PacMap;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

/**
 * 相册ability
 *
 * @author Kirky
 * @version 1.0
 * @date 2022/5/1
 */
public class AlbumAbility extends Ability implements AlbumsSpinner.OnItemSelectedListener,
        MediaProvider.OnMediaClickListener, MediaProvider.CheckStateListener {
    public static final String EXTRA_RESULT_SELECTION = "extra_result_selection";
    public static final String EXTRA_RESULT_SELECTION_PATH = "extra_result_selection_path";
    public static final String EXTRA_RESULT_ORIGINAL_ENABLE = "extra_result_original_enable";
    public static final int REQUEST_CODE_PREVIEW = 23;
    public static final int RESULT_OK = 204;
    public static final String CHECK_STATE = "checkState";
    private final SelectedItemCollection mSelectedCollection = new SelectedItemCollection(this);
    private final ArrayList<Item> list = new ArrayList<>();
    private final ArrayList<Album> albums = new ArrayList<>();
    private final EventHandler handler = new EventHandler(EventRunner.getMainEventRunner());
    private Image ivBack;
    private Text tvTitle;
    private Text tvPreview;
    private Text tvApply;
    private ListContainer listContainer;
    private DirectionalLayout emptyLayout;
    private DirectionalLayout dlCheck;
    private CheckRadioView checkRadioView;
    private Text textCheck;
    private SelectionSpec mSpec;
    private ResultSetLoader loader;
    private AlbumLoader albumLoader;
    private MediaProvider provider;
    private AlbumsAdapter albumsAdapter;
    private AlbumsSpinner albumsSpinner;
    private boolean mOriginalEnable = false;
    private int mSelectedColor = 2001640;
    private int mUnSelectUdColor = 8421504;
    private Album album;
    private final LoaderCallback<ResultSet> loaderCallback = var1 -> AlbumAbility.this.handler.postTask(() -> {
        ArrayList<Item> var1x = new ArrayList<>();
        if (var1.goToFirstRow()) {
            do {
                String var2 = var1.getString(var1.getColumnIndexForName("mime_type"));
                Item var9;
                if (AlbumAbility.this.album != null) {
                    if (MimeType.isVideo(var2) || MimeType.isImage(var2)) {
                        if (!AlbumAbility.this.album.isAll()) {
                            String var3 = var1.getString(var1.getColumnIndexForName("_data"));
                            int var4 = var3.lastIndexOf("/");
                            if (var4 >= 0) {
                                String var5 = var3.substring(0, var4);
                                int var6 = var5.lastIndexOf("/");
                                String var7 = var5.substring(var6 + 1);
                                if (AlbumAbility.this.album.getDisplayName(AlbumAbility.this).equals(var7)) {
                                    Item var8 = Item.valueOf(var1);
                                    var1x.add(var8);
                                }
                            }
                        } else {
                            var9 = Item.valueOf(var1);
                            var1x.add(var9);
                        }
                    }
                } else if (MimeType.isVideo(var2) || MimeType.isImage(var2)) {
                    var9 = Item.valueOf(var1);
                    var1x.add(var9);
                }
            } while (var1.goToNextRow());
        }

        var1.close();
        if (var1x.isEmpty()) {
            AlbumAbility.this.emptyLayout.setVisibility(0);
            AlbumAbility.this.listContainer.setVisibility(2);
            AlbumAbility.this.list.clear();
        } else {
            AlbumAbility.this.emptyLayout.setVisibility(2);
            AlbumAbility.this.listContainer.setVisibility(0);
            AlbumAbility.this.list.clear();
            AlbumAbility.this.list.addAll(var1x);
        }

        AlbumAbility.this.provider.notifyDataChanged();
    });
    private boolean isAll = true;
    private final LoaderCallback<ResultSet> albumCallback = var1 -> AlbumAbility.this.handler.postTask(new Runnable() {
        @Override
        public void run() {
            var1.goToFirstRow();
            Album var1x = Album.valueOf(var1);
            ArrayList<Album> var2 = new ArrayList<>();

            do {
                Album var3 = Album.valueOf(var1);
                var2.add(var3);
            } while (var1.goToNextRow());

            if (!var2.isEmpty()) {
                var1.close();
                AlbumAbility.this.albums.clear();
                AlbumAbility.this.albums.addAll(var2);
                AlbumAbility.this.albumsAdapter.notifyDataChanged();
                AlbumAbility.this.albumsSpinner.setSelection(AlbumAbility.this, 0);
                if (var1x.isAll() && SelectionSpec.getInstance().capture) {
                    var1x.addCaptureCount();
                }

                AlbumAbility.this.onAlbumSelected(var1x);
            }
        }
    });

    public AlbumAbility() {
    }

    private void setStatusBar() {
        getWindow().setStatusBarVisibility(WindowManager.LayoutConfig.MOD_APPLICATION_MEDIA);
        getWindow().setStatusBarColor(ResourceHelper.getColorInt(getContext(),
                ResourceTable.Color_commonly_default, 0xFF87CEFF));
        DisplayManager displayManager = DisplayManager.getInstance();
        Point realPoint = new Point();
        displayManager.getDefaultDisplay(getContext()).get().getRealSize(realPoint);
        Point point = new Point();
        displayManager.getDefaultDisplay(getContext()).get().getSize(point);
        int height = realPoint.getPointYToInt() - point.getPointYToInt();

        Component statusBar = new Component(getContext());
        statusBar.setLayoutConfig(new DirectionalLayout.LayoutConfig(
                DirectionalLayout.LayoutConfig.MATCH_PARENT, height
        ));
        DirectionalLayout layout = findComponentById(ResourceTable.Id_album_statusBar);
        layout.addComponent(statusBar);
    }

    @Override
    public void onStart(Intent var1) {
        this.mSpec = SelectionSpec.getInstance();
        if (!this.mSpec.hasInited) {
            this.terminateAbility(0);
        } else {
            super.onStart(var1);
            super.setUIContent(ResourceTable.Layout_slice_album);
            setStatusBar();
            try {
                this.getWindow().setStatusBarColor(this.getResourceManager().getElement(ResourceTable.Color_zhihu_primary_dark).getColor());
            } catch (NotExistException | WrongTypeException | IOException var7) {
                this.getWindow().setStatusBarColor(Color.WHITE.getValue());
            }

            if (this.mSpec.needOrientationRestriction()) {
                this.setDisplayOrientation(this.mSpec.orientation);
            }

            this.ivBack = this.findComponentById(ResourceTable.Id_imageMatisse_back);
            this.tvTitle = this.findComponentById(ResourceTable.Id_textMatisse_title);
            this.tvPreview = this.findComponentById(ResourceTable.Id_textMatisse_preview);
            this.tvApply = this.findComponentById(ResourceTable.Id_textMatisse_apply);
            this.listContainer = this.findComponentById(ResourceTable.Id_listMatisse);
            this.emptyLayout = this.findComponentById(ResourceTable.Id_emptyMatisse);
            this.dlCheck = this.findComponentById(ResourceTable.Id_dlCheckMatisse);
            this.checkRadioView = this.findComponentById(ResourceTable.Id_checkMatisse_check);
            this.textCheck = this.findComponentById(ResourceTable.Id_textMatisse_check);
            SelectionSpec var3 = SelectionSpec.getInstance();
            int var2;
            if (var3.gridExpectedSize > 0) {
                var2 = UIUtils.spanCount(this.getContext(), var3.gridExpectedSize);
            } else {
                var2 = var3.spanCount;
            }

            TableLayoutManager var4 = new TableLayoutManager();
            var4.setColumnCount(var2);
            this.listContainer.setLayoutManager(var4);
            this.mSelectedCollection.onCreate(null);
            this.provider = new MediaProvider(this.getContext(), this.list, this.mSelectedCollection, var2);
            this.provider.registerCheckStateListener(this);
            this.listContainer.setItemProvider(this.provider);
            this.albumsAdapter = new AlbumsAdapter(this, this.albums);
            this.albumsSpinner = new AlbumsSpinner(this, this.tvTitle);
            this.albumsSpinner.setOnItemSelectedListener(this);
            this.albumsSpinner.setSelectedTextView(this.tvTitle);
            this.albumsSpinner.setAdapter(this.albumsAdapter);
            this.albumLoader = new AlbumLoader(this);
            this.albumLoader.load();
            this.albumLoader.setLoaderCallback(this.albumCallback);
            this.provider.registerOnMediaClickListener(this);

            try {
                this.mSelectedColor = this.getContext().getResourceManager().getElement(ResourceTable.Color_zhihu_item_checkCircle_backgroundColor).getColor();
                this.mUnSelectUdColor = this.getContext().getResourceManager().getElement(ResourceTable.Color_zhihu_check_original_radio_disable).getColor();
            } catch (NotExistException | WrongTypeException | IOException var6) {
                L.d(var6.getMessage());
            }

            this.updateBottomToolbar();
            this.ivBack.setClickedListener(this::clickListener);
            this.tvPreview.setClickedListener(this::clickListener);
            this.tvApply.setClickedListener(this::clickListener);
            this.dlCheck.setClickedListener(this::clickListener);
        }
    }

    @Override
    public void onSaveAbilityState(PacMap var1) {
        super.onSaveAbilityState(var1);
        this.mSelectedCollection.onSaveInstanceState(var1);
        var1.putBooleanValue("checkState", this.mOriginalEnable);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (this.loader != null) {
            this.loader.cancel(true);
        }

        if (this.albumLoader != null) {
            this.albumLoader.cancel(true);
        }

        this.handler.removeAllEvent();
    }

    private void clickListener(Component var1) {
        int var2 = var1.getId();
        if (var2 == ResourceTable.Id_imageMatisse_back) {
            this.terminateAbility();
        } else if (var2 == ResourceTable.Id_dlCheckMatisse) {
            int var3 = this.countOverMaxSize();
            if (var3 > 0) {
                IncapableDialog var4 = new IncapableDialog(this.getContext());

                try {
                    var4.setMessage(this.getResourceManager().getElement(ResourceTable.String_error_over_original_count).getString(var3, this.mSpec.originalMaxSize));
                } catch (NotExistException | WrongTypeException | IOException var6) {
                    var4.setMessage(String.format("%1$d images over %2$d MB. Original will be unchecked", var3, this.mSpec.originalMaxSize));
                }

                var4.setPositiveButton().show();
            }

            this.mOriginalEnable = !this.mOriginalEnable;
            this.checkRadioView.setChecked(this.mOriginalEnable);
            this.textCheck.setTextColor(new Color(this.mOriginalEnable ? this.mSelectedColor : this.mUnSelectUdColor));
            if (this.mSpec.onCheckedListener != null) {
                this.mSpec.onCheckedListener.onCheck(this.mOriginalEnable);
            }
        } else {
            Intent var7;
            if (var2 == ResourceTable.Id_textMatisse_apply) {
                var7 = new Intent();
                ArrayList var8 = (ArrayList) this.mSelectedCollection.asListOfUri();
                var7.setSequenceableArrayListParam("extra_result_selection", var8);
                ArrayList var5 = (ArrayList) this.mSelectedCollection.asListOfString();
                var7.setStringArrayListParam("extra_result_selection_path", var5);
                var7.setParam("extra_result_original_enable", this.mOriginalEnable);
                this.setResult(204, var7);
                this.terminateAbility();
            } else if (var2 == ResourceTable.Id_textMatisse_preview) {
                var7 = new Intent();
                var7.setSequenceableArrayListParam("state_selection", new ArrayList(this.mSelectedCollection.getItems()));
                var7.setParam("state_collection_type", this.mSelectedCollection.getCollectionType());
                var7.setParam("extra_result_original_enable", this.mOriginalEnable);
                Operation var9 = (new Intent.OperationBuilder()).withDeviceId("").withBundleName(this.getBundleName()).withAbilityName(SelectPreviewAbility.class.getName()).build();
                var7.setOperation(var9);
                this.startAbilityForResult(var7, 23);
            }
        }

    }

    @Override
    public void onItemSelected(ListContainer var1, Component var2, int var3, long var4) {
        this.album = (Album) this.albumsAdapter.getItem(var3);
        if (this.album.isAll() && SelectionSpec.getInstance().capture) {
            this.album.addCaptureCount();
        }

        this.onAlbumSelected(this.album);
    }

    private void onAlbumSelected(Album var1) {
        this.isAll = var1.isAll();
        this.loader = new ResultSetLoader(this, SelectionSpec.getInstance().capture);
        this.loader.setLoaderCallback(this.loaderCallback);
        this.loader.load();
    }

    @Override
    public void onNothingSelected(ListContainer var1) {
    }

    @Override
    public void onMediaSelect(Album var1, Item var2, int var3) {
        Intent var4;
        if (var2.isCapture()) {
            var4 = new Intent();
            Operation var5 = (new Intent.OperationBuilder())
                    .withDeviceId("")
                    .withBundleName(this.getBundleName())
                    .withAbilityName(IdentityAbility.class.getName()).build();
            var4.setOperation(var5);
            this.startAbilityForResult(var4, 912);
        } else {
            var4 = new Intent();
            ArrayList var7 = new ArrayList(this.provider.getList());
            if (this.mSpec.capture) {
                var7.remove(0);
            }


            var4.setSequenceableArrayListParam("extra_item_list", var7);
            var4.setSequenceableArrayListParam("state_selection", new ArrayList(this.mSelectedCollection.getItems()));
            var4.setParam("state_collection_type", this.mSelectedCollection.getCollectionType());
            if (this.isAll && this.mSpec.capture) {
                var4.setParam("index", var3 - 1);
            } else {
                var4.setParam("index", var3);
            }

            var4.setParam("extra_result_original_enable", this.mOriginalEnable);
            Operation var6 = (new Intent.OperationBuilder()).
                    withDeviceId("")
                    .withBundleName(this.getBundleName())
                    .withAbilityName(AlbumPreviewAbilityR.class.getName())
                    .build();
            var4.setOperation(var6);
            this.startAbilityForResult(var4, 23);
        }

    }

    @Override
    protected void onAbilityResult(int var1, int var2, Intent var3) {
        super.onAbilityResult(var1, var2, var3);
        if (var2 == 204) {
            try {
                if (var3 != null) {
                    ArrayList var4;
                    Intent var6;
                    if (var1 == 912) {
                        var4 = new ArrayList();
                        ArrayList var5 = new ArrayList();
                        var5.add(var3.getStringParam("file_path"));
                        var4.add(var3.getSequenceableParam("uri"));
                        var6 = new Intent();
                        var6.setSequenceableArrayListParam("extra_result_selection", var4);
                        var6.setStringArrayListParam("extra_result_selection_path", var5);
                        this.setResult(204, var6);
                        this.terminateAbility();
                    } else if (var1 == 23) {
                        var4 = var3.getSequenceableArrayListParam("state_selection");
                        this.mOriginalEnable = var3.getBooleanParam("extra_result_original_enable", false);
                        int var12 = var3.getIntParam("state_collection_type", 0);
                        if (var3.getBooleanParam("extra_result_apply", false)) {
                            var6 = new Intent();
                            ArrayList var7 = new ArrayList();
                            ArrayList var8 = new ArrayList();
                            if (var4 != null) {
                                Iterator var9 = var4.iterator();

                                while (var9.hasNext()) {
                                    Item var10 = (Item) var9.next();
                                    var7.add(var10.getContentUri());
                                    var8.add(var10.data);
                                }
                            }

                            var6.setSequenceableArrayListParam("extra_result_selection", var7);
                            var6.setStringArrayListParam("extra_result_selection_path", var8);
                            var6.setParam("extra_result_original_enable", this.mOriginalEnable);
                            this.setResult(204, var6);
                            this.terminateAbility();
                        } else {
                            this.mSelectedCollection.overwrite(var4, var12);
                            this.provider.notifyDataChanged();
                            this.updateBottomToolbar();
                        }
                    }
                }

            } catch (Exception var11) {
                throw new ClassCastException("Class Exception");
            }
        }
    }

    @Override
    public void onUpdate() {
        this.updateBottomToolbar();
        if (this.mSpec.onSelectedListener != null) {
            this.mSpec.onSelectedListener.onSelected(this.mSelectedCollection.asListOfUri(), this.mSelectedCollection.asListOfString());
        }

    }

    private void updateBottomToolbar() {
        int var1 = this.mSelectedCollection.count();
        if (var1 == 0) {
            this.tvPreview.setEnabled(false);

            this.tvApply.setText(ResourceHelper.getString(this,
                    ResourceTable.String_selected, "选择", null));
            this.tvApply.setTextColor(ResourceHelper.getColor(this,
                    ResourceTable.Color_zhihu_bottom_toolbar_apply_text, 1291876313));
            this.tvPreview.setTextColor(ResourceHelper.getColor(this,
                    ResourceTable.Color_zhihu_bottom_toolbar_preview_text, 1291845632));

            this.tvApply.setEnabled(false);
        } else if (var1 == 1 && this.mSpec.singleSelectionModeEnabled()) {
            this.tvPreview.setEnabled(true);

            this.tvApply.setText(ResourceHelper.getString(this,
                    ResourceTable.String_selected, "选择", null));
            this.tvApply.setTextColor(ResourceHelper.getColor(this,
                    ResourceTable.Color_zhihu_bottom_toolbar_apply_text, 30681));
            this.tvPreview.setTextColor(ResourceHelper.getColor(this,
                    ResourceTable.Color_zhihu_bottom_toolbar_preview_text, -570425344));

            this.tvApply.setEnabled(true);
        } else {
            this.tvPreview.setEnabled(true);
            this.tvApply.setEnabled(true);

            System.out.println("------>" + var1);
            this.tvApply.setText(ResourceHelper.getString(this,
                    ResourceTable.String_button_apply, "Apply", var1));
            this.tvApply.setTextColor(ResourceHelper.getColor(this,
                    ResourceTable.Color_zhihu_bottom_toolbar_apply_text, 30681));
            this.tvPreview.setTextColor(ResourceHelper.getColor(this,
                    ResourceTable.Color_zhihu_bottom_toolbar_preview_text, -570425344));
        }

        if (this.mSpec.originalable) {
            this.dlCheck.setVisibility(0);
            this.updateOriginalState();
        } else {
            this.dlCheck.setVisibility(1);
        }

    }

    private void updateOriginalState() {
        this.checkRadioView.setChecked(this.mOriginalEnable);
        if (this.countOverMaxSize() > 0 && this.mOriginalEnable) {
            IncapableDialog var1 = new IncapableDialog(this.getContext());

            try {
                var1.setMessage(this.getResourceManager().getElement(ResourceTable.String_error_over_original_size).getString(this.mSpec.originalMaxSize));
            } catch (NotExistException | WrongTypeException | IOException var3) {
                var1.setMessage(String.format("Can\\'t select the images larger than %1$d MB", this.mSpec.originalMaxSize));
            }

            var1.setPositiveButton().show();
            this.checkRadioView.setChecked(false);
            this.mOriginalEnable = false;
        }

    }

    private int countOverMaxSize() {
        int var1 = 0;
        int var2 = this.mSelectedCollection.count();

        for (int var3 = 0; var3 < var2; ++var3) {
            Item var4 = this.mSelectedCollection.asList().get(var3);
            if (var4.isImage()) {
                float var5 = PhotoMetadataUtils.getSizeInMB(var4.size);
                if (var5 > (float) this.mSpec.originalMaxSize) {
                    ++var1;
                }
            }
        }

        return var1;
    }
}
